package com.softeem.idriveserver.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.idriveserver.dto.Result;
import com.softeem.idriveserver.entity.Admin;
import com.softeem.idriveserver.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "管理员管理")   //控制器类描述
@CrossOrigin    //允许来自任意源的请求
@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Operation(summary = "管理员新增",description = "需要提供管理员的账号和密码")   //接口方法说明
    @Parameters({   //请求参数说明
            @Parameter(name = "username",description = "账号",required = true),
            @Parameter(name = "password",description = "密码",required = true)
    })
    @PostMapping("/admin")
    public Result add(String username, String password){
        //检查管理员是否重复  select * from admin where username=?
        Admin admin = adminService.getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUsername,username));
        if(admin != null){
            return Result.fail().setMsg("该管理员已存在");
        }
        //生成一个随机盐
        String token = RandomUtil.randomString(16);
        password = password + token;
        //对组合后的密码加密
        password = SecureUtil.md5(password);
        admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        admin.setToken(token);
        return adminService.save(admin) ? Result.ok().setMsg("添加成功").setData(admin) : Result.fail().setMsg("添加失败");
    }

    /**
     * 管理员登录
     */
    @Operation(summary = "管理员登录",description = "需要提供账号和密码")
    @Parameters({
            @Parameter(name = "username",description = "账号",required = true),
            @Parameter(name = "password",description = "密码",required = true)
    })
    @PostMapping("/admin/login")
    public Result login(String username, String password){
        //根据用户名查询管理员信息
        Admin admin = adminService.getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUsername,username));
        if(admin == null){
            return Result.fail().setMsg("该管理员不存在");
        }
        //将输入的密码和随机盐组合
        password = password + admin.getToken();
        //使用md5对组合后的密码加密
        password =SecureUtil.md5(password);
        //判断密码是否正确
        if(!password.equals(admin.getPassword())){
            return Result.fail().setMsg("密码错误");
        }
        //判断账号是否禁用
        if(admin.getStatus() == 0){
            return Result.fail().setMsg("账号禁用");
        }
        //登录成功
        //信息脱敏
        admin.setPassword("******");
        admin.setToken("******");
        return Result.ok().setMsg("登录成功").setData(admin);
    }

    /**
     * 分页查询管理员列表
     * @param page
     * @param limit
     * @return
     */
    @Operation(summary = "管理员列表",description = "分页查询管理员列表")
    @Parameters({
            @Parameter(name = "page",description = "页码",required = false),
            @Parameter(name = "limit",description = "每页数据条数",required = false)
    })
    @GetMapping("/admin/list")
    public Result list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "3") Integer limit){
        //分页查询
        List<Admin> list = adminService.list(new Page<Admin>(page,limit));
        //查询总数据条数
        long count = adminService.count();
        //返回结果
        return Result.ok().setData(list).setMsg("查询成功").setCount(count);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Operation(summary = "删除管理员",description = "根据id删除管理员")
    @Parameters({
            @Parameter(name = "id",description = "管理员id",required = true)
    })
    @DeleteMapping("/admin/{id}")
    public Result delete(@PathVariable Integer id){
        return adminService.removeById(id) ? Result.ok().setMsg("删除成功") : Result.fail().setMsg("删除失败");
    }

    /**
     * 修改账号信息
     */
    @Operation(summary = "修改账号信息",description = "修改账号信息")
    @PutMapping("/admin")
    public Result modify(@RequestBody Admin admin){
        System.out.println(admin+"-------");
        //其他修改判断暂定
        return adminService.updateById(admin) ? Result.ok().setMsg("修改成功") : Result.fail().setMsg("修改失败");
    }

    @Operation(summary = "修改密码",description = "修改密码")
    @Parameters({
            @Parameter(name = "id",description = "管理员id",required = true),
            @Parameter(name = "oldPwd",description = "原始密码",required = true),
            @Parameter(name = "newPwd",description = "新密码",required = true)
    })
    @PutMapping("/admin/pwd")
    public Result modifyPwd(Integer id, String oldPwd, String newPwd){
        Admin admin = adminService.getById(id);
        if(admin == null){
            return Result.fail().setMsg("该管理员不存在");
        }
        //将原始密码和token组合
        oldPwd = oldPwd + admin.getToken();
        oldPwd = SecureUtil.md5(oldPwd);
        if(!oldPwd.equals(admin.getPassword())){
            return Result.fail().setMsg("原始密码错误");
        }
        //重新生成token
        String token = RandomUtil.randomString(16);
        newPwd = newPwd + token;
        newPwd = SecureUtil.md5(newPwd);
        admin.setToken(token);
        admin.setPassword(newPwd);
        return adminService.updateById(admin) ? Result.ok().setMsg("修改成功") : Result.fail().setMsg("修改失败");
    }
}
